<template>
  <div class="main" style="width: 100%;height:100%;overflow-y: auto;">
    <ul style="list-style-type: none; padding-top: 10px; padding-left: 20px; padding-right: 20px; margin: 0px;">
      <li 
        v-for="(item, index) in Store.$state.AITeach.Step4.content"
        :key="index"
        class="content-item"
        :style="{
          borderLeft: '4px solid #409EFF',
          display: displayMode ? (currentDisplayIndex >= index ? 'block' : 'none') : 'block'
        }"
      >
        <!-- 题目序号和内容 -->
        <div style="display: flex; align-items: flex-start; margin-bottom: 10px;">
          <div style="font-weight: bold; color: #409EFF; min-width: 24px;">{{ index + 1 }}、</div>
          <div 
            class="content-text"
            :contenteditable="!displayMode"
            @blur="updateQuestionContent(index, $event)"
            :style="{ 
              outline: 'none', 
              borderBottom: !displayMode ? '1px dashed #ccc' : 'none',
              padding: '2px 4px',
              minHeight: '1.6em',
              width: '100%'
            }"
          >
            <span v-if="displayMode">{{ displayedQuestions[index] || item.content }}</span>
            <span v-else>{{ item.content }}</span>
          </div>
        </div>

        <!-- 图片区域 -->
        <div 
          v-if="item.image?.length"
          style="display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0;"
        >
          <div 
            v-for="(img, imgIndex) in item.image" 
            :key="img.uid || imgIndex"
            :style="{
              display: !displayMode || currentImageIndices[index] >= imgIndex ? 'block' : 'none'
            }"
            style="transition: opacity 0.5s; position: relative; width: 100%; max-width: 300px;"
          >
            <el-image 
              style="height: 150px; width: 100%; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);" 
              :src="getImageUrl(img)"
              :preview-src-list="getPreviewList(item.image)"
              :initial-index="imgIndex"
              fit="cover"
              hide-on-click-modal
              :z-index="9999"
            >
              <template #error>
                <div class="image-slot" style="height: 150px; display: flex; align-items: center; justify-content: center; flex-direction: column;">
                  <el-icon style="font-size: 40px; color: #ccc;"><icon-picture /></el-icon>
                  <span style="margin-top: 8px; color: #999;">图片加载失败</span>
                </div>
              </template>
              <template #placeholder>
                <div class="image-loading" style="height: 150px; display: flex; align-items: center; justify-content: center;">
                  <el-icon style="font-size: 30px; color: #ccc;"><icon-picture /></el-icon>
                </div>
              </template>
            </el-image>
            <button 
              v-if="!displayMode"
              @click="removeImage(index, imgIndex)"
              class="delete-image-btn"
            >
              ×
            </button>
          </div>
        </div>
        
        <!-- 图片上传区域 -->
        <div v-if="!displayMode" style="margin: 10px 0;">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="(file:any) => handleImageUpload(index, file)"
            :before-upload="beforeImageUpload"
            accept="image/jpeg,image/png,image/gif"
            multiple
          >
            <el-button type="primary" size="small" icon="Plus" style="width:70px;">添加图片</el-button>
            <template #tip>
              <div class="el-upload__tip" style="font-size: 12px; color: #888; margin-top: 5px;">
                支持JPG/PNG/GIF格式，单张不超过5MB
              </div>
            </template>
          </el-upload>
        </div>

        <!-- 答案区域 -->
        <div 
          v-if="!displayMode || questionStates[index] > 1"
          style="margin-top: 15px; padding: 10px; background-color: #f8f9fa; border-radius: 6px;"
        >
          <div style="font-weight: bold; color: #409EFF; margin-bottom: 5px;">答案：</div>
          <div 
            class="content-text"
            :contenteditable="!displayMode"
            @blur="updateQuestionAnswer(index, $event)"
            :style="{ 
              outline: 'none', 
              borderBottom: !displayMode ? '1px dashed #ccc' : 'none',
              padding: '2px 4px',
              minHeight: '1.6em'
            }"
          >
            <span v-if="displayMode">{{ displayedAnswers[index] || item.answer }}</span>
            <span v-else>{{ item.answer }}</span>
          </div>
        </div>

        <!-- 删除题目按钮 -->
        <div v-if="!displayMode" style="text-align: right; margin-top: 10px;">
          <el-button 
            type="primary" 
            size="small" 
            @click="removeQuestion(index)"
            :disabled="Store.$state.AITeach.Step4.content.length <= 1"
            icon="Delete"
            style="width:70px;"
          >
            删除题目
          </el-button>
        </div>
      </li>
    </ul>

    <!-- 添加题目按钮 -->
    <div v-if="!displayMode" style="padding: 0 20px 20px;">
      <el-button 
        type="primary" 
        @click="addNewQuestion"
        style="width: 100%;"
        icon="Plus"
      >
        添加题目
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useCounterStore } from '@/stores/counter';
const Store = useCounterStore();
import { ref, onMounted, watch, nextTick } from 'vue';
import { Picture as IconPicture, Plus, Delete } from '@element-plus/icons-vue';
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

interface ImageItem {
  uid: number;
  url: string;
  name?: string;
  type?: string;
  size?: number;
  lastModified?: number;
}

// 显示模式：true=逐字显示，false=直接显示
const displayMode = ref(true);

// 当前显示到的题目索引
const currentDisplayIndex = ref(0);
// 每道题的显示状态：0-题目,1-图片,2-答案
const questionStates = ref<number[]>([]);
// 每道题当前显示的图片索引
const currentImageIndices = ref<number[]>([]);
// 每道题逐字显示的题目内容
const displayedQuestions = ref<string[]>([]);
// 每道题逐字显示的答案内容
const displayedAnswers = ref<string[]>([]);
const isAnimating = ref(false);

const emit = defineEmits<{
  (e: 'toNextStep', param: number): void;
}>();

// 获取图片URL（修复预览问题）
const getImageUrl = (img: any): string => {
  if (!img) return '';
  
  // 如果是base64数据，直接返回
  if (typeof img === 'string' && img.startsWith('data:image')) {
    return img;
  }
  
  // 如果是对象，获取url
  const url = typeof img === 'string' ? img : img?.url;
  if (!url) return '';
  
  // 处理相对路径或无效URL
  try {
    new URL(url);
    return url;
  } catch {
    // 如果是相对路径，尝试转换为绝对路径
    if (url.startsWith('/')) {
      return window.location.origin + url;
    }
    return '';
  }
};

// 获取预览列表（修复预览问题）
const getPreviewList = (images: any[]): string[] => {
  if (!images || !Array.isArray(images)) return [];
  
  return images
    .map(img => getImageUrl(img))
    .filter(url => url !== '');
};

// 更新题目内容
const updateQuestionContent = (index: number, event: Event) => {
  const newContent = (event.target as HTMLElement).innerText;
  Store.$state.AITeach.Step4.content[index].content = newContent;
};

// 更新题目答案
const updateQuestionAnswer = (index: number, event: Event) => {
  const newAnswer = (event.target as HTMLElement).innerText;
  Store.$state.AITeach.Step4.content[index].answer = newAnswer;
};

// 删除题目
const removeQuestion = (index: number) => {
  if (Store.$state.AITeach.Step4.content.length > 1) {
    Store.$state.AITeach.Step4.content.splice(index, 1);
    ElMessage.success('题目已删除');
  } else {
    ElMessage.warning('至少需要保留一道题目');
  }
};

// 添加新题目
const addNewQuestion = () => {
  const newQuestion = {
    content: '请在此输入题目内容',
    answer: '请在此输入题目答案',
    image: []
  };
  Store.$state.AITeach.Step4.content.push(newQuestion);
  ElMessage.success('新题目已添加');
  
  // 滚动到新添加的题目
  nextTick(() => {
    const container = document.querySelector('.main');
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  });
};

// 删除图片
const removeImage = (questionIndex: number, imageIndex: number) => {
  Store.$state.AITeach.Step4.content[questionIndex].image.splice(imageIndex, 1);
  ElMessage.success('图片已删除');
};

// 图片上传前的验证
const beforeImageUpload = (file: File) => {
  const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
  const isImage = validTypes.includes(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只支持JPG/PNG/GIF格式的图片!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!');
    return false;
  }
  return true;
};

// 处理图片上传（修复预览问题）
const handleImageUpload = (questionIndex: number, file: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '图片上传中...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      loading.close();
      
      if (!e.target?.result) {
        ElMessage.error('图片读取失败');
        return reject(false);
      }

      // 创建符合类型要求的图片对象
      const newImage: ImageItem = {
        uid: Date.now(), // 使用时间戳作为唯一ID
        url: e.target.result as string, // 使用base64数据
        name: file.name,
        type: file.raw.type,
        size: file.raw.size,
        lastModified: file.raw.lastModified
      };
      
      // 确保图片数组存在
      if (!Store.$state.AITeach.Step4.content[questionIndex].image) {
        Store.$state.AITeach.Step4.content[questionIndex].image = [];
      }
      
      Store.$state.AITeach.Step4.content[questionIndex].image.push(newImage);
      ElMessage.success('图片添加成功');
      resolve(true);
    };
    reader.onerror = (error) => {
      loading.close();
      console.error('图片读取错误:', error);
      ElMessage.error('图片读取失败');
      reject(false);
    };
    reader.readAsDataURL(file.raw);
  });
};

// 重置显示状态
const resetDisplay = () => {
  const count = Store.$state.AITeach.Step4.content?.length || 0;
  currentDisplayIndex.value = 0;
  questionStates.value = new Array(count).fill(0);
  currentImageIndices.value = new Array(count).fill(-1);
  displayedQuestions.value = new Array(count).fill('');
  displayedAnswers.value = new Array(count).fill('');

  if (displayMode.value && count > 0) {
    startDisplayQuestion(0);
  }
};

// 开始逐字显示题目
const startDisplayQuestion = (index: number) => {
  if (!displayMode.value) return;

  const fullText = Store.$state.AITeach.Step4.content[index].content;
  displayedQuestions.value[index] = '';
  isAnimating.value = true;

  let i = 0;
  const timer = setInterval(() => {
    if (i < fullText.length) {
      displayedQuestions.value[index] = fullText.substring(0, i + 1);
      i++;
    } else {
      clearInterval(timer);
      isAnimating.value = false;
      questionStates.value[index] = 1;
      startDisplayImages(index);
    }
  }, 30);
};

// 开始逐张显示图片
const startDisplayImages = (index: number) => {
  if (!displayMode.value) return;

  const images = Store.$state.AITeach.Step4.content[index].image;
  if (!images || images.length === 0) {
    questionStates.value[index] = 2;
    startDisplayAnswer(index);
    return;
  }

  currentImageIndices.value[index] = 0;
  const timer = setInterval(() => {
    if (currentImageIndices.value[index] < images.length - 1) {
      currentImageIndices.value[index]++;
    } else {
      clearInterval(timer);
      questionStates.value[index] = 2;
      startDisplayAnswer(index);
    }
  }, 800);
};

// 开始逐字显示答案
const startDisplayAnswer = (index: number) => {
  if (!displayMode.value) return;

  const fullText = Store.$state.AITeach.Step4.content[index].answer;
  displayedAnswers.value[index] = '';
  isAnimating.value = true;

  let i = 0;
  const timer = setInterval(() => {
    if (i < fullText.length) {
      displayedAnswers.value[index] = fullText.substring(0, i + 1);
      i++;
    } else {
      clearInterval(timer);
      isAnimating.value = false;
      // 自动显示下一题
      if (index < Store.$state.AITeach.Step4.content.length - 1) {
        currentDisplayIndex.value = index + 1;
        startDisplayQuestion(index + 1);
      } else {
        emit('toNextStep', 5);
      }
    }
  }, 30);
};

// 监听内容变化
watch(() => Store.$state.AITeach.Step4.content, (newVal) => {
  if (newVal && newVal.length > 0) {
    resetDisplay();
  }
}, { immediate: true, deep: true });

onMounted(async () => {
  if (Store.$state.AITeach.Step4.content.length === 0) {
    try {
      const response = await axios({
        url: "https://m1.apifoxmock.com/m1/5997017-0-default/teacher/exercise/generatedbytext",
        method: "GET",
        params: {
          text: Store.$state.AIClassQuestion
        },
        timeout: 10000 // 10秒超时
      });
      
      if (response.data.code === 1) {
        const exercises = response.data.data.exercise.map((item: any) => ({
          ...item,
          content: item.content || '无题目内容',
          answer: item.answer || '无答案内容',
          image: (item.image || []).map((img: any, idx: number) => ({
            ...img,
            uid: img.uid || Date.now() + idx,
            url: img.url ? ensureAbsoluteUrl(img.url) : '' // 确保URL是绝对路径
          })).filter((img: any) => img.url) // 过滤无效URL
        }));
        
        Store.addAIteachStep4(exercises);
      } else {
        throw new Error(response.data.message || 'API返回错误');
      }
    } catch (error) {
      console.error("获取数据失败:", error);
      ElMessage.error('获取题目数据失败: ' + (error as Error).message);
      
      // 使用默认数据避免页面空白
      Store.addAIteachStep4([{
        content: '示例题目',
        answer: '示例答案',
        image: []
      }]);
      displayMode.value = false;
    }
  } else {
    displayMode.value = false;
  }
});

// 确保URL是绝对路径
const ensureAbsoluteUrl = (url: string): string => {
  try {
    new URL(url);
    return url; // 已经是绝对URL
  } catch {
    // 如果是相对路径，转换为绝对路径
    if (url.startsWith('/')) {
      return window.location.origin + url;
    }
    // 其他情况返回空字符串
    return '';
  }
};
</script>

<style scoped>
.main {
  scroll-behavior: smooth;
}

.main::-webkit-scrollbar {
  width: 6px;
  background-color: #f3f4f8;
}

.main::-webkit-scrollbar-track {
  background: #e3e6e9e3;
}

.main::-webkit-scrollbar-thumb {
  background: #c2d0df;
  border-radius: 6px;
}

.main::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0;
}

.content-item {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.content-item:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.content-text {
  font-size: 15px;
  color: #333;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  min-height: 1.6em;
  overflow: hidden;
}

[contenteditable="true"] {
  transition: all 0.3s;
}

[contenteditable="true"]:hover {
  background-color: #f5f7fa;
}

[contenteditable="true"]:focus {
  border-bottom: 1px solid #409EFF !important;
  background-color: #f0f7ff;
}

.image-slot {
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  border-radius: 6px;
  border: 1px dashed #dcdfe6;
}

.image-slot .el-icon {
  font-size: 40px;
  color: #ccc;
  margin-bottom: 8px;
}

.image-slot span {
  font-size: 14px;
  color: #999;
}

.delete-image-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(255, 79, 79, 0.7);
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  opacity: 0.7;
}

.delete-image-btn:hover {
  opacity: 1;
  transform: scale(1.1);
}

/* 修复预览层z-index问题 */
.el-image-viewer__wrapper {
  z-index: 10000 !important;
}
</style>